﻿#region
/**
 * $Date: 0001/1/1
*/
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using BuXiaChu.OrderDishes.DAL.DataAccess;
using BuXiaChu.OrderDishes.Model;
#endregion

namespace BuXiaChu.OrderDishes.DAL
{
    public class OrderItemDAL
    {
        #region private const
        private const string PARAM_ORDER_ITEM_ID = "@OrderItemId";
        private const string PARAM_RESTAURANT_ID = "@RestaurantId";
        private const string PARAM_RESTAURANT_NAME = "@RestaurantName";
        private const string PARAM_DISHES_ID = "@DishesId";
        private const string PARAM_DISHES_NAME = "@DishesName";
        private const string PARAM_ORDER_INFO_ID = "@OrderInfoId";
        private const string PARAM_NUMBER = "@Number";
        private const string PARAM_PRICE = "@Price";
        private const string PARAM_UNIT = "@Unit";
        private const string PARAM_DISCOUNT = "@Discount";
        private const string PARAM_REMARKS = "@Remarks";
        private const string PARAM_CREATE_DATE = "@CreateDate";
        private const string PARAM_STATUS = "@Status";
        private const string PARAM_BOX = "@Box";
        private const string PARAM_BOX_UNIT_PRICE = "@BoxUnitPrice";

        private static readonly string ConnectionString = SQLHelper.CONNECTION_STRING;
        #endregion

        private static void FillModelFrom(SqlDataReader reader, OrderItemModel obj)
        {
            #region
            if (reader != null && !reader.IsClosed)
            {
                obj.OrderItemId = reader.IsDBNull(reader.GetOrdinal("OrderItemId")) ? 0 : reader.GetInt32(reader.GetOrdinal("OrderItemId"));
                obj.RestaurantId = reader.IsDBNull(reader.GetOrdinal("RestaurantId")) ? 0 : reader.GetInt32(reader.GetOrdinal("RestaurantId"));
                obj.RestaurantName = reader.IsDBNull(reader.GetOrdinal("RestaurantName")) ? String.Empty : reader.GetString(reader.GetOrdinal("RestaurantName"));
                obj.DishesId = reader.IsDBNull(reader.GetOrdinal("DishesId")) ? 0 : reader.GetDecimal(reader.GetOrdinal("DishesId"));
                obj.DishesName = reader.IsDBNull(reader.GetOrdinal("DishesName")) ? String.Empty : reader.GetString(reader.GetOrdinal("DishesName"));
                obj.OrderInfoId = reader.IsDBNull(reader.GetOrdinal("OrderInfoId")) ? 0 : reader.GetInt64(reader.GetOrdinal("OrderInfoId"));
                obj.Number = reader.IsDBNull(reader.GetOrdinal("Number")) ? 0 : reader.GetInt32(reader.GetOrdinal("Number"));
                obj.Price = reader.IsDBNull(reader.GetOrdinal("Price")) ? 0 : reader.GetDecimal(reader.GetOrdinal("Price"));
                obj.Unit = reader.IsDBNull(reader.GetOrdinal("Unit")) ? 0 : reader.GetInt32(reader.GetOrdinal("Unit"));
                obj.Discount = reader.IsDBNull(reader.GetOrdinal("Discount")) ? 0 : reader.GetInt32(reader.GetOrdinal("Discount"));
                obj.Remarks = reader.IsDBNull(reader.GetOrdinal("Remarks")) ? String.Empty : reader.GetString(reader.GetOrdinal("Remarks"));
                obj.CreateDate = reader.IsDBNull(reader.GetOrdinal("CreateDate")) ? DateTime.MinValue : reader.GetDateTime(reader.GetOrdinal("CreateDate"));
                obj.Status = reader.IsDBNull(reader.GetOrdinal("Status")) ? Convert.ToByte(0) : reader.GetByte(reader.GetOrdinal("Status"));
                obj.Box = reader.IsDBNull(reader.GetOrdinal("Box")) ? Convert.ToByte(0) : reader.GetByte(reader.GetOrdinal("Box"));
                obj.BoxUnitPrice = reader.IsDBNull(reader.GetOrdinal("BoxUnitPrice")) ? 0 : reader.GetDecimal(reader.GetOrdinal("BoxUnitPrice"));
            }
            #endregion
        }

        private static SqlParameter[] GetOrderItemParams(OrderItemModel obj)
        {
            #region
            SqlParameter[] dbParams ={					
					 SQLHelper.MakeParam(PARAM_ORDER_ITEM_ID, SqlDbType.Int,0,obj.OrderItemId),
					 SQLHelper.MakeParam(PARAM_RESTAURANT_ID, SqlDbType.Int,0,obj.RestaurantId),
					 SQLHelper.MakeParam(PARAM_RESTAURANT_NAME, SqlDbType.NVarChar, 50,obj.RestaurantName),					
					 SQLHelper.MakeParam(PARAM_DISHES_ID, SqlDbType.Decimal,0,obj.DishesId),
					 SQLHelper.MakeParam(PARAM_DISHES_NAME, SqlDbType.NVarChar, 20,obj.DishesName),					
					 SQLHelper.MakeParam(PARAM_ORDER_INFO_ID, SqlDbType.BigInt,0,obj.OrderInfoId),
					 SQLHelper.MakeParam(PARAM_NUMBER, SqlDbType.Int,0,obj.Number),
					 SQLHelper.MakeParam(PARAM_PRICE, SqlDbType.Money,0,obj.Price),
					 SQLHelper.MakeParam(PARAM_UNIT, SqlDbType.Int,0,obj.Unit),
					 SQLHelper.MakeParam(PARAM_DISCOUNT, SqlDbType.Int,0,obj.Discount),
					 SQLHelper.MakeParam(PARAM_REMARKS, SqlDbType.NVarChar, 128,obj.Remarks),					
					 SQLHelper.MakeParam(PARAM_STATUS, SqlDbType.TinyInt,0,obj.Status),
					 SQLHelper.MakeParam(PARAM_BOX, SqlDbType.TinyInt,0,obj.Box),
					 SQLHelper.MakeParam(PARAM_BOX_UNIT_PRICE, SqlDbType.Money,0,obj.BoxUnitPrice),
                     SQLHelper.MakeOutParam("@ResultId",SqlDbType.Int ,0,0)
			};

            return dbParams;
            #endregion
        }

        public static bool Save(OrderItemModel obj)
        {
            #region
            try
            {
                SqlParameter[] dbParams = GetOrderItemParams(obj);

                if (obj.OrderItemId == 0)
                {
                    obj.OrderItemId = Convert.ToInt32(SQLHelper.ExecuteScalar(ConnectionString, CommandType.StoredProcedure, "OrderItem_InsertUpdate", dbParams));
                    return obj.OrderItemId > 0 ? true : false;
                }
                else
                {
                    var affectNum = SQLHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "OrderItem_InsertUpdate", dbParams);
                    return affectNum > 0 ? true : false;
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("OrderItem-->InsertOrUpdate-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }

            return false;
            #endregion
        }

        public static bool Save(List<OrderItemModel> orderItemList, long orderInfoId, SqlTransaction tran)
        {
            #region
            try
            {
                foreach (var item in orderItemList)
                {
                    item.OrderInfoId = orderInfoId;
                    SqlParameter[] dbParams = GetOrderItemParams(item);
                    SQLHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, "OrderItem_InsertUpdate", dbParams);
                    if (dbParams[dbParams.Length - 1].Value != DBNull.Value)
                    {
                        item.OrderItemId = int.Parse(dbParams[dbParams.Length - 1].Value.ToString());
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                Exception ex = new Exception("OrderItem-->InsertOrUpdate-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }

            return false;
            #endregion
        }

        public static OrderItemModel GetByOrderItemId(int orderItemId)
        {
            #region
            SqlDataReader reader = null;
            OrderItemModel obj = new OrderItemModel();

            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_ORDER_ITEM_ID, SqlDbType.Int, 0, orderItemId)
                    };

                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "OrderItem_GetByOrderItemId", dbParams);

                if (reader.Read())
                {
                    FillModelFrom(reader, obj);
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("OrderItem-->GetSingleObject-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return obj;
            #endregion
        }

        public static bool Delete(int orderItemId)
        {
            #region
            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_ORDER_ITEM_ID, SqlDbType.Int, 0, orderItemId)
                    };

                return SQLHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "OrderItem_Delete", dbParams) > 0 ? true : false;
            }
            catch (Exception e)
            {
                Exception ex = new Exception("OrderItem-->Delete-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            return false;
            #endregion
        }

        public static Dictionary<long, List<OrderItemModel>> Search(string sqlWhere, int pageIndex, int pageSize, out int pageCount)
        {
            #region
            Dictionary<long, List<OrderItemModel>> result = new Dictionary<long, List<OrderItemModel>>();
            pageCount = 0;
            try
            {
                if (string.IsNullOrEmpty(sqlWhere))
                {
                    sqlWhere = " 1=1 ";
                }

                SqlParameter[] dbParams =
                {
                    SQLHelper.MakeParam("@sqlWhere", SqlDbType.NVarChar,0,sqlWhere),
                    SQLHelper.MakeParam("@pageIndex",SqlDbType.Int,0,pageIndex),
                    SQLHelper.MakeParam("@pageSize",SqlDbType.Int,0,pageSize),
                    SQLHelper.MakeOutParam("@pageCount", SqlDbType.Int,0,0)                    
                };
                using (SqlDataReader reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "OrderItem_Search", dbParams))
                {
                    while (reader.Read())
                    {
                        OrderItemModel model = new OrderItemModel();
                        FillModelFrom(reader, model);
                        if (result.ContainsKey(model.OrderInfoId))
                        {
                            result[model.OrderInfoId].Add(model);
                        }
                        else
                        {
                            var itemList = new List<OrderItemModel>();
                            itemList.Add(model);
                            result.Add(model.OrderInfoId, itemList);
                        }
                    }
                }
                pageCount = int.Parse(dbParams[3].Value.ToString());
            }
            catch (Exception e)
            {
                Exception ex = new Exception("OrderItem-->Search-->" + e.ToString());
                ExceptionMessageDAL.Record(ex);
            }
            return result;
            #endregion
        }
    }
}
